﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace PreContractWeb.Task
{
    public partial class EditPreContractInfo : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Joan 2008-10-22 disable autopostback
            if (btnDelete.Attributes["autopostback"] == null)
                btnDelete.Attributes.Add("autopostback", "false");

            Page.Header.Controls.Add(new LiteralControl(@"<base target=""_self"" />"));

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (!Page.IsPostBack)
            {
                btnDelete.Attributes.Add("onClick", "OnCommentsDelete();");
                btnSave.Visible = false;
                btnNewComment.Visible = false;
                btnDelete.Visible = false;
                btnDelete.Visible = false;
                if (Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString()))
                {
                    chkMustModifyDR.Visible = true;
                    btnNewComment.Visible = true;
                    btnDelete.Visible = true;
                }
                if (Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString()) ||
                    Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Editer.ToString()))
                {
                    btnSave.Visible = true;

                    pnlView.Visible = false;
                }
                else
                {
                    pnlEdit.Visible = false;
                }

                string id = Page.Request.QueryString["id"];

                PreContractID = id;

                bool hasFirstText = false;

                if (((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).CommentAllowed)
                {
                    btnNewComment.Visible = true;
                    //this.btnDelete.Visible = true;
                }
                if (id == "0")
                {
                    btnNewComment.Visible = false;
                    btnDelete.Visible = false;
                }

                if (Page.Request.QueryString["ismain"] != null)
                {
                    btnCancel.Visible = false;
                }

                BaseFunction.BindContractStatusDropDownList(ddlStatus, string.Empty, hasFirstText);

                BaseFunction.BindContractTypeDropDownList(ddlType, string.Empty, hasFirstText);

                BaseFunction.BindBDDropDownList(ddlBD, string.Empty, hasFirstText);

                BaseFunction.BindCATDropDownList(ddlCAT, string.Empty, hasFirstText);

                BaseFunction.BindProvinceDropDownList(ddlProvince, string.Empty, hasFirstText);

                //
                BaseFunction.BindContractAdjustDropDownList(ddlContractAdjust, string.Empty, true);

                BaseFunction.BindClusterDropDownList(ddlCluster, string.Empty, true);

                InitData();
            }

            if (returnvalue != null && returnvalue.Value != "")
            {
                BindGridView();

                returnvalue.Value = "";

                string id = Page.Request.QueryString["id"];

                if (id == null) return;

                BEGDC.PreContract.BLL.IPreContractInfo precontractService = (BEGDC.PreContract.BLL.IPreContractInfo)
                    BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfo_Service];
                BEGDC.PreContract.DAL.PreContractInfo precontract = precontractService.GetPreContractInfo(int.Parse(id));

                chkRisk.Checked = precontract.IsRisk;
            }
        }

        private string PreContractID
        {
            get
            {
                if (Session["PreContractID"] == null) return "0";

                return (string)Session["PreContractID"];
            }
            set { Session["PreContractID"] = value; }
        }

        private int CommentsCount
        {
            get
            {
                if (ViewState["CommentsCount"] == null) return 0;

                return (int)ViewState["CommentsCount"];
            }
            set { ViewState["CommentsCount"] = value; }
        }

        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ddlCluster.SelectedIndex = 0;

            if (this.ddlProvince.SelectedIndex > 0)
            {
                BEGDC.PreContract.DAL.Province province = BEGDC.PreContract.DAL.Province.Find(int.Parse(this.ddlProvince.SelectedItem.Value));
                this.ddlCluster.SelectedIndex = ddlCluster.Items.IndexOf(ddlCluster.Items.FindByValue(province.ClusterID.ToString()));
            }
        }

        private void BindGridView()
        {
            BEGDC.PreContract.BLL.IPreContractInfoComment commentservice = (BEGDC.PreContract.BLL.IPreContractInfoComment)
                BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfoComment_Service];
            System.Data.DataTable dt = commentservice.GetPreContractInfoCommentView(string.Format(" PreContractID = {0}", PreContractID));

            CommentsCount = dt.Rows.Count;

            if (!Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString()))
            {
                gvMain.Columns[2].Visible = false;
            }
            gvMain.DataSource = dt.DefaultView;
            gvMain.DataBind();
        }

        private void InitData()
        {
            string id = Page.Request.QueryString["id"];

            if (id == null)
                return;

            if (id == "0")
                return;

            //判断权限. 如果不是admin, 则判断是否有权限
            if (!Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString()))
            {
                string strpermission = ((BEGDC.PreContract.BLL.Authentication.PCPrincipal)Page.User).DataPermission;
                BEGDC.PreContract.BLL.IPreContractInfo contractservice =
                    (BEGDC.PreContract.BLL.IPreContractInfo)
                    BEGDC.Utility.Castle.AppContainer.Instance[
                        BEGDC.PreContract.BLL.Services.CONST_PreContractInfo_Service];

                strpermission += " AND PreContractID = " + id;
                System.Data.DataTable dt = contractservice.GetPreContractInfo(strpermission);
                if (dt.Rows.Count == 0)
                    return;
            }
            BEGDC.PreContract.BLL.IPreContractInfo precontractService =
                (BEGDC.PreContract.BLL.IPreContractInfo)
                BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfo_Service];
            BEGDC.PreContract.DAL.PreContractInfo precontract = precontractService.GetPreContractInfo(int.Parse(id));

            if (precontract == null)
            {
                return;
            }

            txtPreContractID.Text = precontract.PreContractID.ToString();
            txtPreContractNo.Text = precontract.PreContractNo;
            txtPreContractNo.ReadOnly = true;

            ddlStatus.SelectedValue = precontract.StatusID.DicItemID.ToString();
            ddlType.SelectedValue = precontract.TypeID.DicItemID.ToString();

            txtProductID.Text = precontract.ProductID.ProductID.ToString();
            txtProduct.Text = precontract.ProductID.ProductName;

            ddlBD.SelectedValue = precontract.BDID.BDID.ToString();

            if (precontract.CEWPromised.HasValue)
                txtCEWPromised.Text = Math.Round(precontract.CEWPromised.Value, 2).ToString();

            if (precontract.OrionPrice.HasValue)
                txtOrionPrice.Text = Math.Round(precontract.OrionPrice.Value, 2).ToString();

            if (precontract.SalePrice.HasValue)
                txtSalesPrice.Text = Math.Round(precontract.SalePrice.Value, 2).ToString();

            if (precontract.SignDue.HasValue)
                txtSignDue.Text = precontract.SignDue.Value.ToString("yyyy-MM-dd");
            if (precontract.SignActual.HasValue)
                txtSignActual.Text = precontract.SignActual.Value.ToString("yyyy-MM-dd");

            txtAdvancedContract.Text = precontract.AdvancedContract;

            ddlProvince.SelectedValue = precontract.ProvinceID.ProvinceID.ToString();
            ddlCAT.SelectedValue = precontract.CATID.CATID.ToString();

            if (precontract.PromisedDate.HasValue)
                txtPromisedDate.Text = precontract.PromisedDate.Value.ToString("yyyy-MM-dd");
            txtContractName.Text = precontract.ContractName;
            txtCustomerName.Text = precontract.CustomerName;

            if (precontract.ERPReceived.HasValue)
                txtERPRecvd.Text = precontract.ERPReceived.Value.ToString("yyyy-MM-dd");
            txtOrionNo.Text = precontract.OrionNo;

            if (precontract.Delivered)
                chkDelivery.Checked = true;
            else
                chkDelivery.Checked = false;

            if (precontract.DeliveryPercent.HasValue)
            {
                lblDeliveryPercentage.Text = precontract.DeliveryPercent.Value.ToString();
                txtDeliveryPercentage.Text = precontract.DeliveryPercent.Value.ToString();
            }
            if (precontract.Flag.HasValue)
            {
                lblFlag.Text = precontract.Flag.Value.ToString();
            }
            txtCurrentSituation.Text = precontract.CurrentSituation;

            BEGDC.PreContract.BLL.IExchangeRate rateservice =
                (BEGDC.PreContract.BLL.IExchangeRate)
                BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_ExchangeRate_Service];
            System.Decimal rate = rateservice.GetExchangeRate();

            if (precontract.SparePrice.HasValue)
                txtCEWME.Text =
                    Convert.ToString(Math.Round((precontract.SparePrice.Value / rate / BaseFunction.CONST_Million), 2));
            else
                txtCEWME.Text = "0";

            if (precontract.OrionPrice.HasValue)
                txtOrionME.Text =
                    Convert.ToString(Math.Round((precontract.OrionPrice.Value / rate / BaseFunction.CONST_Million), 2));
            else
                txtOrionME.Text = "0";

            txtGAP.Text = Convert.ToString((Convert.ToDecimal(txtOrionME.Text) - Convert.ToDecimal(txtCEWME.Text)));

            if (precontract.TradeMonth.HasValue)
                txtTradeMonth.Text = precontract.TradeMonth.Value.ToString("MM");
            txtTradeMonth.ReadOnly = true;

            txtBG.Text = precontract.BDID.BGID.BGCode;
            txtBG.ReadOnly = true;

            if (precontract.ModifiedDate.HasValue)
            {
                DateTime date = System.Convert.ToDateTime(precontract.ModifiedDate.Value);
                txtModified.Text = date.ToString("yyyy-MM-dd") + " " + date.ToShortTimeString();
            }
            txtModified.ReadOnly = true;

            if (precontract.BlackDate.HasValue)
                txtBlackDate.Text = precontract.BlackDate.Value.ToString("yyyy-MM-dd");

            txtARCNO.Text = precontract.ACRNo;

            if (precontract.ASBorLucent)
            {
                rdoASB.Checked = false;
                rdoLucent.Checked = true;
            }
            else
            {
                rdoASB.Checked = true;
                rdoLucent.Checked = false;
            }

            txtApply.Text = precontract.Applicant;
            txtApplyEmail.Text = precontract.ApplicantEmail;
            txtPrincipalName.Text = precontract.Principal;
            txtPrincipalEmail.Text = precontract.PrincipalEmail;

            chkRisk.Checked = precontract.IsRisk;

            if (precontract.AOGDate != null)
                this.txtAOGDate.Text = precontract.AOGDate.Value.ToString("yyyy-MM-dd");

            if (precontract.DeadlineOfTrying != null)
            {
                this.txtDeadlineOfTrying.Text = precontract.DeadlineOfTrying.Value.ToString("yyy-MM-dd");
            }

            this.txtTransferHisInfo.Text = precontract.TransferHistoryInfo;

            if (precontract.SpecialApprove != null && precontract.SpecialApprove.IndexOf("1") > -1)
                chkSpecialApprove1.Checked = true;
            if (precontract.SpecialApprove != null && precontract.SpecialApprove.IndexOf("2") > -1)
                chkSpecialApprove2.Checked = true;
            if (precontract.SpecialApprove != null && precontract.SpecialApprove.IndexOf("3") > -1)
                chkSpecialApprove3.Checked = true;
            if (precontract.SpecialApprove != null && precontract.SpecialApprove.IndexOf("4") > -1)
                chkSpecialApprove4.Checked = true;



            //View
            chkDelivery_View.Checked = precontract.Delivered;
            lblBD.Text = precontract.BDID.BDCode;
            lblCAT.Text = precontract.CATID.CATName;
            lblCEWME.Text = txtCEWME.Text;
            lblContractName.Text = precontract.ContractName;
            lblERPRecvd.Text = txtERPRecvd.Text;
            lblGAP.Text = txtGAP.Text;
            lblOrionME.Text = txtOrionME.Text;
            lblPreContractNo.Text = precontract.PreContractNo;
            lblPromisedDate.Text = txtPromisedDate.Text;
            lblProvince.Text = precontract.ProvinceID.ProvinceCName;
            lblSignActual.Text = txtSignActual.Text;
            lblStatus.Text = precontract.StatusID.DicItemDesc;
            lblTradeMonth.Text = txtTradeMonth.Text;
            chkIsDelay.Checked = precontract.IsDelay;
            if (precontract.DeliveryDate.HasValue)
                txtDeliveryDate.Text = precontract.DeliveryDate.Value.ToString("yyyy-MM-dd");

            //added by yuliang 2010-5-15
            BEGDC.PreContract.DAL.Province province = BEGDC.PreContract.DAL.Province.Find(int.Parse(this.ddlProvince.SelectedItem.Value));
            this.ddlCluster.SelectedIndex = ddlCluster.Items.IndexOf(ddlCluster.Items.FindByValue(province.ClusterID.ToString()));

            if (precontract.AdjustID != null && precontract.AdjustID.DicTypeID != null)
                this.ddlContractAdjust.SelectedIndex = ddlContractAdjust.Items.IndexOf(ddlContractAdjust.Items.FindByValue(precontract.AdjustID.DicItemID.ToString()));

            if (precontract.SparePrice != null)
                this.txtSparePrice.Text = Math.Round(precontract.SparePrice.Value, 2).ToString();
            if (precontract.CFIPrice != null)
                this.txtCFI.Text = Math.Round(precontract.CFIPrice.Value, 2).ToString();

            this.txtDeliveryPlan.Text = precontract.DeliveryPlan;
            this.txtUpdateReason.Text = precontract.UpdateReason;

            int EemployeeId = ((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).EmployeeId;
            BEGDC.PreContract.BLL.IUserRole iUserRole = (BEGDC.PreContract.BLL.IUserRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_UserRole_Service];
            DataTable dtEmpRole = iUserRole.GetUserRole_DataTable(String.Format("EmployeeID = {0}", EemployeeId));
            BEGDC.PreContract.DAL.Role role = new BEGDC.PreContract.DAL.Role();
            BEGDC.PreContract.BLL.IRole iRole = (BEGDC.PreContract.BLL.IRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Role_Service];

            bool isCFIRole = false;
            for (int t = 0; t < dtEmpRole.Rows.Count; t++)
            {
                role = iRole.GetRole(Convert.ToInt32(dtEmpRole.Rows[t]["RoleID"].ToString()));
                if (role.Description.Contains("CFI"))
                {
                    isCFIRole = true;
                    break;
                }
            }

            if (isCFIRole == false)
            {
                this.tdCFI.Visible = false;
                this.txtCFI.Visible = false;
            }
            //
            BindGridView();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string id = Page.Request.QueryString["id"];

            if (id == null)
                return;

            try
            {
                BEGDC.PreContract.BLL.IPreContractInfo precontractService = (BEGDC.PreContract.BLL.IPreContractInfo)
                    BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfo_Service];


                bool IsNew = true;

                BEGDC.PreContract.DAL.PreContractInfo precontract = new BEGDC.PreContract.DAL.PreContractInfo();
                if (id != "0")
                {
                    IsNew = false;
                    precontract = precontractService.GetPreContractInfo(int.Parse(id));
                }


                if (!precontractService.IsUnique(IsNew, txtPreContractNo.Text, Convert.ToInt32(ddlBD.SelectedValue)))
                {
                    ClientScript.RegisterStartupScript(GetType(), "",
                                                       "<script>alert('" + AlertMessage.PreContractNotUnique +
                                                       "')</script>");
                    return;
                }

                if (precontract == null)
                    return;

                precontract.PreContractNo = txtPreContractNo.Text;

                BEGDC.PreContract.DAL.DicItem dictStatus = new BEGDC.PreContract.DAL.DicItem();
                dictStatus.DicItemID = Convert.ToInt32(ddlStatus.SelectedValue);
                precontract.StatusID = dictStatus;

                BEGDC.PreContract.DAL.DicItem dictType = new BEGDC.PreContract.DAL.DicItem();
                dictType.DicItemID = Convert.ToInt32(ddlType.SelectedValue);
                precontract.TypeID = dictType;

                //
                BEGDC.PreContract.BLL.IProduct productservice = (BEGDC.PreContract.BLL.IProduct)
                    BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Product_Service];
                BEGDC.PreContract.DAL.Product product = productservice.GetProductByName(txtProduct.Text, true);
                precontract.ProductID = product;

                BEGDC.PreContract.DAL.BD bd = new BEGDC.PreContract.DAL.BD();
                bd.BDID = Convert.ToInt32(ddlBD.SelectedValue);
                precontract.BDID = bd;

                precontract.CEWPromised = Convert.ToDecimal(txtCEWPromised.Text.Trim());
                precontract.OrionPrice = Convert.ToDecimal(txtOrionPrice.Text.Trim());

                if (txtSalesPrice.Text != string.Empty)
                    precontract.SalePrice = Convert.ToDecimal(txtSalesPrice.Text);
                else
                    precontract.SalePrice = 0;

                precontract.SignDue = Convert.ToDateTime(txtSignDue.Text);

                if (txtSignActual.Text.Trim() == string.Empty)
                    precontract.SignActual = null;
                else
                    precontract.SignActual = Convert.ToDateTime(txtSignActual.Text);

                precontract.AdvancedContract = txtAdvancedContract.Text;

                BEGDC.PreContract.DAL.Province province = new BEGDC.PreContract.DAL.Province();
                province.ProvinceID = Convert.ToInt32(ddlProvince.SelectedValue);
                precontract.ProvinceID = province;

                BEGDC.PreContract.DAL.CAT cat = new BEGDC.PreContract.DAL.CAT();
                cat.CATID = Convert.ToInt32(ddlCAT.SelectedValue);
                precontract.CATID = cat;

                precontract.PromisedDate = Convert.ToDateTime(txtPromisedDate.Text);
                precontract.ContractName = txtContractName.Text;
                precontract.CustomerName = txtCustomerName.Text;


                precontract.ERPReceived = Convert.ToDateTime(txtERPRecvd.Text);
                precontract.OrionNo = txtOrionNo.Text;

                if (chkDelivery.Checked)
                    precontract.Delivered = true;
                else
                    precontract.Delivered = false;

                precontract.CurrentSituation = txtCurrentSituation.Text;

                precontract.ModifiedDate = System.DateTime.Now;

                if (txtBlackDate.Text != string.Empty)
                    precontract.BlackDate = Convert.ToDateTime(txtBlackDate.Text);

                precontract.ACRNo = txtARCNO.Text;

                if (rdoASB.Checked)
                    precontract.ASBorLucent = false;
                else
                    precontract.ASBorLucent = true;

                precontract.Applicant = txtApply.Text;
                precontract.ApplicantEmail = txtApplyEmail.Text;
                precontract.Principal = txtPrincipalName.Text;
                precontract.PrincipalEmail = txtPrincipalEmail.Text;
                precontract.IsDelay = chkIsDelay.Checked;
                string strSpecialApprove = "";

                if (chkSpecialApprove1.Checked)
                    strSpecialApprove = "1,";
                if (chkSpecialApprove2.Checked)
                    strSpecialApprove = strSpecialApprove + "2,";
                if (chkSpecialApprove3.Checked)
                    strSpecialApprove = strSpecialApprove + "3,";
                if (chkSpecialApprove4.Checked)
                    strSpecialApprove = strSpecialApprove + "4,";
                if (strSpecialApprove.Length > 0)
                    strSpecialApprove = strSpecialApprove.Substring(0, strSpecialApprove.Length - 1);

                precontract.SpecialApprove = strSpecialApprove;

                //Joan 2008-10-20 don't need to save, it comes from last comment
                //precontract.IsRisk = this.chkRisk.Checked;

                //如果转正. 必须保证承诺,预计, 最终转正金额一致.
                if (Convert.ToInt32(ddlStatus.SelectedValue) == (int)BEGDC.PreContract.BLL.DicItem.PreContractStatus.Won)
                {
                    // delete. alan  2008-11-25
                    //if (precontract.CEWPromised != precontract.SalePrice || precontract.SalePrice != precontract.OrionPrice)
                    //{
                    //    this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + AlertMessage.DataSame + "')</script>");
                    //    return;
                    //}

                    if (txtSignActual.Text == string.Empty)
                    {
                        ClientScript.RegisterStartupScript(GetType(), "",
                                                           "<script>alert('" + AlertMessage.FinalDateNotEmpty +
                                                           "')</script>");
                        return;
                    }

                    if (precontract.SignDue != precontract.SignActual)
                    {
                        ClientScript.RegisterStartupScript(GetType(), "",
                                                           "<script>alert('" + AlertMessage.DateSame + "')</script>");
                        return;
                    }
                    //precontract.SalePrice = precontract.CEWPromised;
                    //precontract.OrionPrice = precontract.CEWPromised;
                }

                BEGDC.PreContract.BLL.ICloseDate closedateservice = (BEGDC.PreContract.BLL.ICloseDate)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CloseDate_Service];
                precontract.TradeMonth = closedateservice.GetTradeMonth_Date(precontract.SignDue.Value);
                Nullables.NullableDateTime dtDeliveryDate = null;
                if (txtDeliveryDate.Text != string.Empty)
                    dtDeliveryDate = Convert.ToDateTime(txtDeliveryDate.Text);
                if (chkMustModifyDR.Checked)
                {
                    lblFlag.Text = "";
                }

                //
                //added by yuliang 2010-5-15
                if (Convert.ToInt32(ddlContractAdjust.SelectedValue) < 0)
                {
                    ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('请选择合同分类！')</script>");
                    return;
                }
                BEGDC.PreContract.DAL.DicItem dictAdjust = new BEGDC.PreContract.DAL.DicItem();
                dictAdjust.DicItemID = Convert.ToInt32(ddlContractAdjust.SelectedValue);
                precontract.AdjustID = dictAdjust;

                precontract.SparePrice = Convert.ToDecimal(this.txtSparePrice.Text.Trim());
                precontract.CFIPrice = String.IsNullOrEmpty(this.txtCFI.Text.Trim()) ? 0 : Convert.ToDecimal(this.txtCFI.Text.Trim());
                precontract.DeliveryPlan = this.txtDeliveryPlan.Text.Trim();
                precontract.UpdateReason = this.txtUpdateReason.Text.Trim();

                if (!String.IsNullOrEmpty(this.txtAOGDate.Text.Trim()))
                    precontract.AOGDate = Convert.ToDateTime(this.txtAOGDate.Text.Trim());
                else
                    precontract.AOGDate = null;

                if (!String.IsNullOrEmpty(this.txtDeadlineOfTrying.Text.Trim()))
                    precontract.DeadlineOfTrying = Convert.ToDateTime(this.txtDeadlineOfTrying.Text.Trim());
                else
                    precontract.DeadlineOfTrying = null;

                precontract.TransferHistoryInfo = this.txtTransferHisInfo.Text.Trim();


                //yuliang 以下逻辑在“导入转正信息”中
                if (Convert.ToInt32(ddlStatus.SelectedValue) == (int)BEGDC.PreContract.BLL.DicItem.PreContractStatus.Won)
                {
                    //precontract.SparePrice = 0; //全部转正时，承诺剩余金额=0
                }
                else if (Convert.ToInt32(ddlStatus.SelectedValue) == (int)BEGDC.PreContract.BLL.DicItem.PreContractStatus.PartWon)
                {
                    //precontract.SparePrice = 
                }

                //
                if (id == "0")
                {
                    if (txtDeliveryPercentage.Text != string.Empty)
                        precontract.DeliveryPercent = Convert.ToDecimal(txtDeliveryPercentage.Text);
                    precontract.CreateAndFlush();
                }
                else
                {
                    if (chkMustModifyDR.Checked)
                        precontract.Flag = null;
                    decimal currentPercentage = 0;
                    if (txtDeliveryPercentage.Text != string.Empty)
                        currentPercentage = Convert.ToDecimal(txtDeliveryPercentage.Text);
                    if (dtDeliveryDate == null)
                    {
                        if (currentPercentage >= 0 && currentPercentage < 20)
                        {
                            precontract.Flag = null;
                        }
                        else if (currentPercentage >= 20 && currentPercentage < 100)
                        {
                            precontract.Flag = 1;
                        }
                        else if (currentPercentage == 100)
                        {
                            precontract.Flag = 2;
                        }
                        precontract.DeliveryPercent = currentPercentage;
                        precontract.DeliveryDate = dtDeliveryDate;
                    }
                    else
                    {
                        if (lblFlag.Text == string.Empty)
                        {
                            precontract.DeliveryPercent = currentPercentage;
                            precontract.DeliveryDate = dtDeliveryDate;
                            if (currentPercentage >= 20 && currentPercentage < 100)
                            {
                                precontract.Flag = 1;
                            }
                            else if (currentPercentage == 100)
                            {
                                precontract.Flag = 2;
                            }
                        }
                        else if (lblFlag.Text == "1")
                        {
                            if (currentPercentage >= 0 && currentPercentage < 20)
                            {
                                precontract.DeliveryPercent = currentPercentage;
                                precontract.DeliveryDate = dtDeliveryDate;
                                precontract.Flag = null;
                            }
                            else if (currentPercentage >= 20 && currentPercentage < 100)
                            {
                                precontract.DeliveryPercent = currentPercentage;
                            }
                            else if (currentPercentage == 100)
                            {
                                precontract.DeliveryPercent = currentPercentage;
                                precontract.DeliveryDate = dtDeliveryDate;
                                precontract.Flag = 2;
                            }
                        }

                    }
                    precontract.Update();
                }

                BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.EditPreContract,
                                       string.Format("Pre-Contract No:{0}; BD: {1}", precontract.PreContractNo,
                                                     ddlBD.SelectedItem.Text), User.Identity.Name);


                if (Page.Request.QueryString["ismain"] != null)
                    Page.Response.Redirect(Page.Request.Url.AbsoluteUri.Replace("id=0",
                                                                                "id=" +
                                                                                precontract.PreContractID.ToString()));
                else
                {
                    string script = "var arr=new Array(); arr[0]='" + "Save" + "';window.returnValue=arr;";
                    Page.Response.Write(BaseFunction.GetAlertByReturnValue(true, script));
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(GetType(), "",
                                                   "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        protected void gvMain_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString()) || Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Editer.ToString()))
            //{

            if (e.Row.RowIndex >= 0)
            {
                LinkButton lnkARID = (LinkButton)e.Row.FindControl("lnkDateCreated");
                lnkARID.Enabled = false;

                if (Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString()))
                {
                    lnkARID.Attributes.Add("onclick", "javascript:ShowPage('" + e.Row.Cells[0].Text.Trim() + "');");
                    lnkARID.Enabled = true;
                }
                //if (e.Row.RowIndex == this.CommentsCount - 1 && ((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).CommentAllowed && (Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString()) || Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Editer.ToString())))
                //{
                //    lnkARID.Attributes.Add("onclick", "javascript:ShowPage('" + e.Row.Cells[0].Text.Trim() + "');");
                //    lnkARID.Enabled = true;
                //}


                lnkARID.Text = e.Row.Cells[1].Text.Trim().Replace("/", "-");
                e.Row.Cells[8].Text = e.Row.Cells[8].Text.Replace("/", "-");
            }
            //}
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            BEGDC.PreContract.BLL.IPreContractInfoComment commentService = (BEGDC.PreContract.BLL.IPreContractInfoComment)
                BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfoComment_Service];
            for (int i = 0; i < gvMain.Rows.Count; i++)
            {
                CheckBox ck = gvMain.Rows[i].FindControl("chkSelect") as CheckBox;

                if (ck.Checked)
                {
                    string commentId = gvMain.Rows[i].Cells[0].Text;

                    commentService.DeletePreContractInfoComment(Convert.ToInt32(commentId));
                }
            }
            BindGridView();
        }


    }
}